import {connect} from "react-redux";
import {action} from "@/store/action/index.js";
import NavBarAgain from "@/components/NavBarAgain.jsx";
import {useState} from "react";
import './Update.scss'
import {ImageUploader, Input} from "antd-mobile/2x";
import {Button, Toast} from "antd-mobile";
import {queryUserUpdate, upload} from "@/api/index.js";

const Update = function Update(props) {
    let {navigate, info, queryUserInfoAsync} = props;
    let [fileList, setFileList] = useState(info.authorImg?[{url:info.authorImg}]:[]),
        [nickname, setNickname] = useState(info.nickname);

    const limitImage = (file) => {
        if (file.size > 1024 * 1024 * 2) {
            Toast.show({
                content: '图片大小不能超过2M',
                duration: 2000,
            })
            return false;
        }
        return file;
    }
    const uploadImage =async (file) => {
        const formData = new FormData();
        formData.append('file', file);
       let {code, data} =  await upload(formData)

        if (code === '200'&& data) {
            //setFileList([{url:pic}])
        }else {
            Toast.show({
                content: '上传失败',
                duration: 2000,
            })
            return
        }
        return {
            url:data.filename
        }
    }
    const onSubmit = async () => {
        if(fileList.length===0){
            Toast.show({
                content: '请上传头像',
                duration: 2000,
            })
            return
        }
        if(nickname.length===0){
            Toast.show({
                content: '请输入昵称',
                duration: 2000,
            })
            return
        }

        await queryUserUpdate({url:fileList[0].url, nickname})

    }

    return <div className="update-box">
        <NavBarAgain title={'个人信息'}></NavBarAgain>

        <div className="update-content">
            <div className="update-item">
                <div className="update-item-title">头像</div>
                <div className="update-item-content">
                    <ImageUploader
                        accept={'image/*'}
                        maxCount={1}
                        beforeUpload={limitImage}
                        upload={uploadImage}
                        onChange={setFileList}
                        value={fileList}
                    />
                </div>
            </div>
            <div className="update-item">
                <div className="update-item-title">昵称</div>
                <div className="update-item-content">
                    <Input type="text" value={nickname} onChange={(e) => setNickname(e)}/>
                </div>
            </div>
            <Button block color={'primary'} onClick={onSubmit}>保存</Button>

        </div>
    </div>
}
export default connect(state => state.base, action.base)(Update)